package com.dnjn.happiness.biz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.biz.domain.Communicate;
import com.dnjn.happiness.biz.domain.CommunicateVO;
import com.dnjn.happiness.biz.service.ICommunicateService;
import com.dnjn.happiness.common.security.utils.VerifyUtil;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.system.api.RemoteDeptService;
import com.dnjn.happiness.system.api.RemoteTeamService;
import com.dnjn.happiness.system.api.domain.SysDept;
import com.dnjn.happiness.system.api.domain.SysTeam;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;


/**
 * 沟通Controller
 *
 * @author happiness
 * @date 2023-10-28
 */
@Tag(name = "biz communicate 沟通", description = "沟通")
@RestController
@RequestMapping("/communicate")
public class CommunicateController extends BaseController {
    @Autowired
    private ICommunicateService communicateService;

    @Autowired
    private RemoteDeptService deptService;

    @Autowired
    private RemoteTeamService teamService;

    /**
     * 修改沟通
     */
    @RequiresPermissions("biz:communicate:edit")
    @Log(title = "沟通", businessType = BusinessType.UPDATE)
    @Operation(summary = "更新沟通", description = "① 结束沟通:传参: communicateStatus:1; ② 填写沟通结果 必传:communicateId(沟通id);result(沟通结果);etypeId(情绪id);communicateStatus(沟通状态改为1)")
    @PutMapping("/updateAdmin")
    public AjaxResult editAdmin(@RequestBody Communicate communicate) {
        Assert.notNull(communicate.getUserId(), "被沟通人不能为空");

        return toAjax(communicateService.updateById(communicate));
    }

    @Log(title = "沟通", businessType = BusinessType.UPDATE)
    @Operation(summary = "更新沟通", description = "① 结束沟通:传参: communicateStatus:1; ② 填写沟通结果 必传:communicateId(沟通id);result(沟通结果);etypeId(情绪id);communicateStatus(沟通状态改为1)")
    @PutMapping("/update")
    public AjaxResult edit(@RequestBody Communicate communicate) {
        Assert.notNull(communicate.getUserId(), "被沟通人不能为空");

        return toAjax(communicateService.updateById(communicate));
    }


    @Log(title = "沟通", businessType = BusinessType.INSERT)
    @Operation(summary = "添加沟通", description = "必传: fromUserId:沟通发起人; userId:沟通人 operUserId:实际沟通人;communicateType是INTERVIEW")
    @PostMapping("/addCommunicate")
    public AjaxResult addCommunicate(@RequestBody Communicate communicate) {
        Long userId = SecurityUtils.getUserId();
        communicate.setFromUserId(userId);
        Assert.notNull(communicate.getFromUserId(), "沟通发起人不能为空");
        Assert.notNull(communicate.getUserId(), "沟通人不能为空");
        Assert.notNull(communicate.getOperUserId(), "实际沟通人不能为空");
        return toAjax(communicateService.toAssignCommunicate(communicate));
    }

    @Log(title = "沟通", businessType = BusinessType.INSERT)
    @Operation(summary = "填写沟通结果", description = "必传: fromUserId:沟通发起人; userId:沟通人 operUserId:实际沟通人;communicateType是INTERVIEW")
    @PostMapping("/addCommunicateResult")
    public AjaxResult addCommunicateResult(@RequestBody Communicate communicate) {
        Long userId = SecurityUtils.getUserId();
        communicate.setFromUserId(userId);
        Assert.notNull(communicate.getFromUserId(), "沟通发起人不能为空");
        Assert.notNull(communicate.getUserId(), "沟通人不能为空");

        Communicate one = communicateService.lambdaQuery().eq(Communicate::getUserId, communicate.getUserId()).ne(Communicate::getCommunicateStatus, '3').one();

        if (null != one) {
            Long communicateId = one.getCommunicateId();
            communicate.setCommunicateId(communicateId);
            communicateService.editResultCommunicate(communicate);
        } else {
            return success("没有等待沟通的");

        }

        return success();
    }

    @Log(title = "沟通", businessType = BusinessType.INSERT)
    @Operation(summary = "查询user_id有没有被指派", description = "必传: userId,查询userId有没有被指派,前端根据返回数据判断显示已指派还是去指派")
    @PostMapping("/queryUserId")
    public AjaxResult queryUserId(@Parameter(required = true) Long userId) {

        QueryWrapper<Communicate> wrapper = new QueryWrapper<>();
        //0 已经指派
        wrapper.eq("user_id", userId).eq("communicate_status", "1");
        Communicate one = communicateService.getOne(wrapper);
        return AjaxResult.success(one);
    }


    @PostMapping("/queryCommunicate")
    @Log(title = "biz", businessType = BusinessType.LIST)
    @Operation(summary = "沟通记录-指派给我的-小程序", description = "① 个人详情-访谈记录 必传: userId 可以选择沟通人 operUserId ; ")
    public AjaxResult queryComByUserId(@RequestBody Communicate domain, @Parameter(required = true) boolean SurveyOrInteview, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        if (SurveyOrInteview) {
            domain.setCommunicateType("SURVEY");//问卷记录
        } else {
            domain.setCommunicateType("INTERVIEW");//访谈
        }
        domain.setType("oper");
        Page<Communicate> list = communicateService.queryComByUserId(domain, Page.of(current, size).addOrder(OrderItem.desc("communicate_id")));

        return success(list);

    }

    // 我的  里边   我的沟通记录
    @PostMapping("/queryCommunicateByMy")
    @Log(title = "biz", businessType = BusinessType.LIST)
    @Operation(summary = "我的沟通-小程序", description = " ② 我的-沟通历史 必传: operUserId 可选:gouTongNickname")
    public AjaxResult queryCommunicateByMy(@RequestBody Communicate domain, @Parameter(required = true) boolean SurveyOrInteview, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        if (SurveyOrInteview) {
            domain.setCommunicateType("SURVEY");//问卷记录
        } else {
            domain.setCommunicateType("INTERVIEW");//访谈
        }
        domain.setType("my");
        if (VerifyUtil.whetherAllPermissions()) {
            domain.setWhetherAllPermissions(true);
        } else {
            domain.setWhetherAllPermissions(false);
        }

        Page<Communicate> list = communicateService.queryComByUserId(domain, Page.of(current, size).addOrder(OrderItem.desc("communicate_id")));

        return success(list);

    }

    //  小程序 -团队  -dto.的
    @PostMapping("/queryCommunicateTeam")
    @Operation(summary = "团队-指派给我的", description = "传operUserId")
    public AjaxResult queryCommunicateTeam(@RequestBody Communicate domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {


        Page<CommunicateVO> list = communicateService.queryCommunicateTeam(domain, Page.of(current, size).addOrder(OrderItem.desc("hlbean")));
//        Page<Communicate> list = communicateService.queryComByUserId(domain, Page.of(current, size).addOrder(OrderItem.desc("communicate_id")));


        communicateService.getCountByUserId(list.getRecords());

        return success(list);

    }

    @RequiresPermissions("biz:communicate:query")
    @PostMapping("/queryCommunicateTeamAdmin")
    @Operation(summary = "团队-指派给我的-后台", description = "传operUserId")
    public AjaxResult queryCommunicateTeamAdmin(@RequestBody Communicate domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {


        Page<CommunicateVO> list = communicateService.queryCommunicateTeam(domain, Page.of(current, size).addOrder(OrderItem.desc("hlbean")));

        communicateService.getCountByUserId(list.getRecords());


        return success(list);

    }


//后台---

    /**
     * 查询沟通列表
     */
    @RequiresPermissions("biz:communicate:list")
    @PostMapping("/list")
    public AjaxResult list(@RequestBody Communicate vo, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        if (VerifyUtil.whetherAllPermissions()) {
            vo.setWhetherAllPermissions(true);
        } else {
            vo.setWhetherAllPermissions(false);
        }
        Page<Communicate> list = communicateService.queryComByUserId(vo, Page.of(current, size).addOrder(OrderItem.desc("score_time")));
        if (!CollectionUtils.isEmpty(list.getRecords())) {
            for (Communicate communicate : list.getRecords()) {
                String operDeptId = communicate.getOperDeptId();
                if (!StringUtils.isEmpty(operDeptId) ) {
                    R<SysDept> result = deptService.getInfoById(Long.parseLong(operDeptId), SecurityConstants.INNER);
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                        communicate.setOperDeptName(result.getData().getDeptName());
                    }
                }
                String userDeptId = communicate.getUserDeptId();
                if (!StringUtils.isEmpty(userDeptId)) {
                    R<SysDept> result = deptService.getInfoById(Long.parseLong(userDeptId), SecurityConstants.INNER);
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                        communicate.setUserDeptName(result.getData().getDeptName());
                    }
                }
            }
        }

        return success(list);
    }


    /**
     * 获取沟通详细信息
     */
    @GetMapping(value = "/{communicateId}")
    public AjaxResult get(@PathVariable("communicateId") Long communicateId) {
        return success(communicateService.getCommunicateIdById(communicateId));
    }

    /**
     * 新增沟通
     */
    //@Log(title = "沟通", businessType = BusinessType.INSERT)
    @RequiresPermissions("biz:communicate:add")
    @PostMapping()
    public AjaxResult add(@RequestBody Communicate vo) {
        Communicate communicate = new Communicate();
        communicate.setCreateBy(SecurityUtils.getUsername());
        return toAjax(communicateService.save(communicate));
    }

    /**
     * 修改沟通
     */
    //@Log(title = "沟通", businessType = BusinessType.UPDATE)
    @RequiresPermissions("biz:communicate:edit")
    @PutMapping()
    public AjaxResult edit1(@RequestBody Communicate vo) {
        Communicate communicate = new Communicate();
        return toAjax(communicateService.updateById(communicate));
    }


    @RequiresPermissions("biz:communicate:remove")
    @DeleteMapping("/{communicate_ids}")
    public AjaxResult remove(@PathVariable Long communicate_ids) {
        return toAjax(communicateService.lambdaUpdate().eq(Communicate::getCommunicateId, communicate_ids).set(Communicate::getDeleted, "1").update());
    }


    @PostMapping("/getCommunicatePage")
    @Operation(summary = "小程序-需沟通列表")
    public AjaxResult getCommunicatePage(@RequestBody Communicate communicate, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page page = Page.of(current, size);
        communicate.setType("queryCommunicate");
//        communicate.setCommunicateStatus("0");
        if (VerifyUtil.whetherAllPermissions()) {
            communicate.setWhetherAllPermissions(true);
        } else {
            communicate.setWhetherAllPermissions(false);
        }
        communicate.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
        Page<Communicate> list = communicateService.getCommunicatePage(page, communicate);
        return success(list);
    }

    /**
     * 小程序-当日已指派
     */
    @PostMapping("/getTodayAssignPage")
    @Operation(summary = "小程序-当日已指派")
    public AjaxResult getTodayAssignPage(@RequestBody Communicate communicate, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page page = Page.of(current, size);
//        communicate.setCommunicateStatus("1");
        communicate.setType("queryTodayAssign");
        if (VerifyUtil.whetherAllPermissions()) {
            communicate.setWhetherAllPermissions(true);
        } else {
            communicate.setWhetherAllPermissions(false);
        }
        communicate.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
        Page<Communicate> list = communicateService.getCommunicatePage(page, communicate);
        return success(list);
    }

    /**
     * 统计当日新增沟通数量
     */
    @GetMapping("/todayCommunicateTotal")
    public AjaxResult todayCommunicateTotal() {
        Communicate domain = new Communicate();
        domain.setCurrDate(LocalDate.now());
        domain.setCommunicateStatus("3");
        if (VerifyUtil.whetherAllPermissions()) {
            domain.setWhetherAllPermissions(true);
        } else {
            domain.setWhetherAllPermissions(false);
        }
        Page<Communicate> list = communicateService.queryComByUserId(domain, Page.of(1, 10).addOrder(OrderItem.desc("communicate_id")));
        return AjaxResult.success(list.getTotal());
    }

    /**
     * 后台首页-需沟通 - 改
     */
    @PostMapping("/getCommunicateListPage")
    @Operation(summary = "后台首页-需沟通- 改")
    public AjaxResult getCommunicateListPage(@RequestBody Communicate communicate, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page page = Page.of(current, size);
//        communicate.setCommunicateStatus("0");
        communicate.setType("queryCommunicate");
        Long userId = SecurityUtils.getUserId();
        communicate.setUserId(userId);
        SysTeam team = null;
        R<SysTeam> result = teamService.getInfoById(userId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            team = result.getData();
        }

        if (VerifyUtil.whetherAllPermissions()) {
            communicate.setWhetherAllPermissions(true);
        } else {
            if (null == team) {
                return success(new Page<Communicate>());
            } else {
                communicate.setTeamId(team.getTeamId());
            }
            communicate.setWhetherAllPermissions(false);
        }

        Page<Communicate> list = communicateService.getPage(page, communicate);
        return success(list);
    }

    /**
     * 首页 查询去指派 -》 执行列表 -改
     * 查询 当前登录用户Id，被沟通人用户id
     * 查看被指派人得上级，和 上上级不是自己的
     *
     * @param :currentUserId 当前登录用户id
     * @param :userId        被沟通人id
     */
    @GetMapping("/newQueryUserListByUserId/{userId}")
    public AjaxResult newQueryUserListByUserId(@PathVariable Long userId) {
        Assert.notNull(userId, "被指派人用户id不能为空");
        List<SysTeam> list = new ArrayList<>();
        //指派人Id
        Long currentUserId = SecurityUtils.getUserId();
        SysTeam currTeam = null;
        R<SysTeam> result = teamService.getInfoById(userId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            currTeam = result.getData();
        }
        if (null == currTeam) {
            return AjaxResult.success(list);
        }
        //当前登陆人的team，
        SysTeam sysTeam = null;
        R<SysTeam> resultCur = teamService.getInfoById(currentUserId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(resultCur) && StringUtils.isNotNull(resultCur.getData())) {
            sysTeam = resultCur.getData();
        }
        if (!ObjectUtils.isEmpty(currTeam.getParentId())) {
            SysTeam parentTeam = null;
            R<SysTeam> resultParentTeam = teamService.queryInfoByTeamId(currTeam.getParentId(), SecurityConstants.INNER);
            if (StringUtils.isNotNull(resultParentTeam) && StringUtils.isNotNull(resultParentTeam.getData())) {
                parentTeam = resultParentTeam.getData();
            }
            if (null != parentTeam) {
                //如果是超级管理员，返回直接上级
                if (VerifyUtil.whetherAllPermissions()) {
                    list.add(parentTeam);
                    return AjaxResult.success(list);
                } else {
                    if (!parentTeam.getUserId().equals(currentUserId) && sysTeam.getLevel() <= parentTeam.getLevel()) {
                        list.add(parentTeam);
                    }
                }
            }
        }
        if (!ObjectUtils.isEmpty(currTeam.getSuperId()) && !VerifyUtil.whetherAllPermissions()) {
            SysTeam superTeam = null;
            R<SysTeam> resultSuperTeam = teamService.queryInfoByTeamId(currTeam.getSuperId(), SecurityConstants.INNER);
            if (StringUtils.isNotNull(resultSuperTeam) && StringUtils.isNotNull(resultSuperTeam.getData())) {
                superTeam = resultSuperTeam.getData();
            }
            if (!superTeam.getUserId().equals(currentUserId) && sysTeam.getLevel() <= superTeam.getLevel()) {
                //不能指派给当前登录人的上级
                if (!ObjectUtils.isEmpty(sysTeam.getParentId()) && !sysTeam.getParentId().equals(superTeam.getTeamId())) {
                    list.add(superTeam);
                }
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 建议查询 查询去指派 -》 执行列表 -改
     * 如果是超级管理员登录那么指派的时候显示该人的所有上级。
     * 普通管理员查看被指派人得上级，和 上上级不是自己的
     * 查询 当前登录用户Id，被沟通人用户id
     *
     * @param :currentUserId 当前登录用户id
     * @param :userId        被沟通人id
     */
    @GetMapping("/newQueryAdviceUserListByUserId/{userId}")
    public AjaxResult newQueryAdviceUserListByUserId(@PathVariable Long userId) {
        Assert.notNull(userId, "被指派人用户id不能为空");
        List<SysTeam> list = new ArrayList<>();
        //指派人Id
        Long currentUserId = SecurityUtils.getUserId();
        SysTeam currTeam = null;
        R<SysTeam> result = teamService.getInfoById(userId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
            currTeam = result.getData();
        }
        if (null == currTeam) {
            return AjaxResult.success(list);
        }
        //如果是超级管理员，递归查询所有上级
        if (VerifyUtil.whetherAllPermissions()) {
            selectTeamByParentTeamId(currTeam, list);
            return AjaxResult.success(list);
        }
        //当前登陆人的team，
        SysTeam sysTeam = null;
        R<SysTeam> resultCur = teamService.getInfoById(currentUserId, SecurityConstants.INNER);
        if (StringUtils.isNotNull(resultCur) && StringUtils.isNotNull(resultCur.getData())) {
            sysTeam = resultCur.getData();
        }
        if (!ObjectUtils.isEmpty(currTeam.getParentId())) {
            SysTeam parentTeam = null;
            R<SysTeam> resultParentTeam = teamService.queryInfoByTeamId(currTeam.getParentId(), SecurityConstants.INNER);
            if (StringUtils.isNotNull(resultParentTeam) && StringUtils.isNotNull(resultParentTeam.getData())) {
                parentTeam = resultParentTeam.getData();
            }
            if (!parentTeam.getUserId().equals(currentUserId) && sysTeam.getLevel() <= parentTeam.getLevel()) {
                list.add(parentTeam);
            }
        }
        if (!ObjectUtils.isEmpty(currTeam.getSuperId())) {
            SysTeam superTeam = null;
            R<SysTeam> resultSuperTeam = teamService.queryInfoByTeamId(currTeam.getSuperId(), SecurityConstants.INNER);
            if (StringUtils.isNotNull(resultSuperTeam) && StringUtils.isNotNull(resultSuperTeam.getData())) {
                superTeam = resultSuperTeam.getData();
            }
            if (!superTeam.getUserId().equals(currentUserId) && sysTeam.getLevel() <= superTeam.getLevel()) {
                //不能指派给当前登录人的上级
                if (!ObjectUtils.isEmpty(sysTeam.getParentId()) && !sysTeam.getParentId().equals(superTeam.getTeamId())) {
                    list.add(superTeam);
                }
            }
        }
        return AjaxResult.success(list);
    }


    public void selectTeamByParentTeamId(SysTeam currTeam, List<SysTeam> list) {
        SysTeam superTeam = null;
        R<SysTeam> resultParentTeam = teamService.queryInfoByTeamId(currTeam.getParentId(), SecurityConstants.INNER);
        if (StringUtils.isNotNull(resultParentTeam) && StringUtils.isNotNull(resultParentTeam.getData())) {
            superTeam = resultParentTeam.getData();
        }
        if (null != superTeam) {
            list.add(superTeam);
            selectTeamByParentTeamId(superTeam, list);
        } else {
            return;
        }
    }
}
